package com.ladlee.validata.processor.impl;

import com.ladlee.validata.ValidataCodeType;
import com.ladlee.validata.ValidateCode;
import com.ladlee.validata.processor.ValidateCodeRepository;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * @Auther: dingchang
 * @Date: 2018/12/21 16:00
 * @Description: 操作验证码的存储实现类
 */
@Component
public class SessionValidataRepository implements ValidateCodeRepository {

    /**
     * 验证码放入session时的前缀
     */
    String SESSION_KEY_PREFIX = "SESSION_KEY_FOR_CODE_";

    /**
     * 操作session的工具类
     */
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidataCodeType validataCodeType) {
        sessionStrategy.setAttribute(request, getSessionKey(validataCodeType), code);
    }

    @Override
    public ValidateCode get(ServletWebRequest request, ValidataCodeType validataCodeType) {
        return (ValidateCode) sessionStrategy.getAttribute(request, getSessionKey(validataCodeType));
    }

    @Override
    public void remove(ServletWebRequest request, ValidataCodeType codaType) {
        sessionStrategy.removeAttribute(request, getSessionKey(codaType));
    }
    /**
     * 构建验证码翻入session得可以
     *
     * @return
     */
    private String getSessionKey(ValidataCodeType validateCodeType) {
        return SESSION_KEY_PREFIX + validateCodeType.toString().toLowerCase();
    }

}
